# -*- coding: utf-8 -*-
"""
@Time : 2023/6/4 13:03
@Author : Gremore
@File : home
@Des: 
"""

from fastapi import Request, APIRouter, Form, Cookie
from fastapi.responses import HTMLResponse
from fastapp.models.base import User, Role
from typing import Optional


router = APIRouter()


@router.get("/", tags=["门户首页"], response_class=HTMLResponse)
async def home(request: Request, session_id: Optional[str] = Cookie(None)):
    """
    门户首页
    :param request:
    :param session_id:
    :return:
    """
    cookie = session_id
    session = request.session.get("session")
    page_data = {
        "cookie": cookie,
        "session": session
    }
    # request.session.setdefault("55555", "hhffdghj")

    return request.app.state.views.TemplateResponse("index.html", {"request": request, **page_data})


@router.get("/reg", tags=["门户首页"], response_class=HTMLResponse)
async def reg_page(req: Request):
    """
    注册页面
    :param req:
    :return: html
    """
    return req.app.state.views.TemplateResponse("reg_page.html", {"request": req})


@router.post("/reg/form", tags=["门户首页"], response_class=HTMLResponse)
async def regret_page(req: Request, username: str = Form(...), password: str = Form(...)):
    """
    注册结果页面
    :param req:
    :param username:
    :param password:
    :return: html
    """

    user_list = await User().all().values()
    for user in user_list:
        print(f"用户:{user.get('username')}", user)

    add_user = await User().create(username=username, password=password)
    print("插入结果：", add_user)
    print("插入用户名：", add_user.username)

    get_user = await User().get_or_none(username=username)
    if not get_user:
        print("注册失败！")
        return {"info":"没有查询到用户"}
    print("查询到的用户：", get_user)

    return req.app.state.views.TemplateResponse("reg_ret.html",
            {"request": req, "username": get_user.username, "password": get_user.password})
